package com.zhgxi.zf.action;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;

import com.zhgxi.zf.entity.Dept;
import com.zhgxi.zf.entity.User;
import com.zhgxi.zf.service.UserService;
import com.zhgxi.zf.util.AMFContext;

@Controller("UserAction")
public class UserAction {

	@Resource
	private UserService userService;

	public boolean login(User user) {
		user = userService.login(user);
		if (user != null) {
			AMFContext context = AMFContext.getCurrentContext();
			context.setSessionAttribute("user", user);
			return true;
		}
		return false;
	}

	public User getUser() {
		AMFContext context = AMFContext.getCurrentContext();
		return (User) context.getSessionAttribute("user");
	}

	public void logOut() {
		AMFContext context = AMFContext.getCurrentContext();
		context.setSessionAttribute("user", null);
	}

	public boolean deleteUser(Integer uid) {
		return userService.deleteUser(uid);
	}

	public List<User> findByUname(String uname) {
		return userService.findByUname(uname);
	}

	/**
	 * @author thrfou
	 */
	public boolean addUser(User user) {
		return userService.saveUser(user);
	}

	/**
	 * @author elemeNT
	 * @return 部门
	 */
	public Dept getDept() {
		return this.getUser().getDept();
	}

	public List<User> findAll() {
		return userService.findAllUser();
	}

	public boolean modifyPwd(String currentPwd, String newPwd) {
		User u = getUser();
		if (!(u.getPassword().equals(currentPwd))) {
			return false;
		}
		u.setPassword(newPwd);
		return userService.saveUser(u);
	}

	public boolean saveInfoPhone(String phoneNum,String email) {
		User u = getUser();
		u.setPhone(phoneNum);
		u.setEmail(email);
		return userService.saveUser(u);
	}

	@InitBinder
	public void InitBinder(WebDataBinder dataBinder) {
		dataBinder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"), false));
	}

}
